package com.phone.dao.impl;

import java.util.List;

import org.hibernate.SessionFactory;
import org.hibernate.query.Query;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.phone.dao.CartDao;
import com.phone.entity.CartItml;
@Repository
public class CartDaoimpl implements CartDao{
	@Autowired
    private SessionFactory sessionFactory;
	@Override
	public void savecart(CartItml cart) {
		this.sessionFactory.getCurrentSession().save(cart);
	}
	@Override
	public List<CartItml> showcart(int uid) {
		List<CartItml> cart=null;
		String hql="from CartItml where uid=?";
		try {
			Query query=this.sessionFactory.getCurrentSession().createQuery(hql);
			query.setParameter(0, uid);
			cart=query.list();
		} catch (Exception e) {
		    e.printStackTrace();
		}
		return cart;
	}
	@Override
	public boolean delcart(Integer id) {
		CartItml cartItml=null;
		try {
			cartItml=this.sessionFactory.getCurrentSession().load(CartItml.class, id);
			if (cartItml.getCount()==1) {
				this.sessionFactory.getCurrentSession().delete(cartItml);
			} else {
				int count=cartItml.getCount()-1;
				int totalprice=count*cartItml.getPrice();
				cartItml.setCount(count);
				cartItml.setTotalprice(totalprice);
				this.sessionFactory.getCurrentSession().update(cartItml);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return true;
	}
	@Override
	public boolean upcart(int id) {
		CartItml cartItml=null;
		try {
			cartItml=this.sessionFactory.getCurrentSession().load(CartItml.class, id);
			int count=cartItml.getCount()+1;
			int totalprice=count*cartItml.getPrice();
			cartItml.setCount(count);
			cartItml.setTotalprice(totalprice);
			this.sessionFactory.getCurrentSession().update(cartItml);
		} catch (Exception e) {
			e.printStackTrace();
			}
		return true;
	}
	@Override
	public void clear(CartItml cartItml) {
		this.sessionFactory.getCurrentSession().delete(cartItml);	
	}
}
